package com.qfedu.controller;

import com.qfedu.entity.ResponseData;
import com.qfedu.entity.User;
import com.qfedu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 用户相关
 */
@RestController
public class UserController {


    @Autowired
    private UserService userService;

    /**
     * 接收用户登录请求
     * @return
     *
     * 1.得到用户名 和 密码 去数据表 user 进行校对
     *
     * 2.返回统一格式的数据
     *
     */
    @RequestMapping("/login.do")
    public ResponseData login(String no, String pass, HttpServletRequest request){

        // 去数据库查询用户名和密码
       List<User> userList =  userService.findUserByNoAndPassword(no,pass);

        ResponseData responseData = new ResponseData();
        // 用户名不重复 size 最大是1
       if (userList.size()>0){// 存在对应的用户和密码 登录成功

           // 登录成功是否需要在session 中记录用户信息
           request.getSession().setAttribute("user", userList.get(0));

           responseData.setCode(0);
           responseData.setMsg("success");
       }else {
           responseData.setCode(1);// 密码或者 账户错误
           responseData.setMsg("fail");
       }

        return responseData;
    }


    /**
     * 判断用户是否已经登录
     * @return
     */
    @RequestMapping("/LoginToJudge.do")
    public ResponseData isLogin(HttpServletRequest request){

        HttpSession httpSession = request.getSession();
        ResponseData responseData = new ResponseData();
        if (httpSession.getAttribute("user")!=null){// 已经登录
            responseData.setCode(0);
            responseData.setMsg("success");
        }else {// 未登录 前端 跳转登录界面
            responseData.setCode(1);
            responseData.setMsg("fail");
        }
        return responseData;
    }

    /**
     * 注销
     * @param request
     * @return
     */
    @RequestMapping("/loginOut.do")
    public ResponseData logout(HttpServletRequest request){
        HttpSession httpSession = request.getSession();

        // 让session 失效
        httpSession.invalidate();

        ResponseData responseData = new ResponseData();
        responseData.setCode(0);
        responseData.setMsg("退出登录成功");

        return responseData;
    }

    /**
     * 获取当前用户信息
     * @param request
     * @return
     */
    @RequestMapping("/findByNo.do")
    public ResponseData getCurrentUser(HttpServletRequest request){
        HttpSession httpSession = request.getSession();
        User user = (User) httpSession.getAttribute("user");

        ResponseData responseData = new ResponseData();

        responseData.setData(user);
        responseData.setCode(0);
        responseData.setMsg("success");

        return responseData;
    }

}
